package servlet;

import entity.Goods;
import model.Picture;
import service.GoodsService;
import service.impl.GoodsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebServlet("/InsertGoodsServlet")
@MultipartConfig
public class InsertGoodsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        //定义session对象
        HttpSession session = request.getSession();
        //定义out对象
        PrintWriter out = response.getWriter();
            //商品名称
        String name = request.getParameter("goodsName");
        Goods goods=new Goods();
        goods.setGoodsName(name);
            //商品价格
        double price = Double.parseDouble(request.getParameter("price"));
        goods.setPrice(price);
            //商品描述
        String describe = request.getParameter("describe");
        goods.setDescribe(describe);
            //商品上架时间
        goods.setGoodsTime(timedatenow());
            //商品库存
        int inventory = Integer.parseInt(request.getParameter("inventory"));
        goods.setInventory(inventory);
            //单位
        String units = request.getParameter("units");
        goods.setUnits(units);
            //商品图片路径
        String url="Picture/";
        //图片绝对路径
        String realPath = getServletContext().getRealPath(url);
        //获取图片
        Part filePath = request.getPart("filePath");

        //获取 图片路径+名称
        Picture picture=new Picture();
        String s = picture.filesUploadModel(filePath, realPath);

        String location=url+s;
        goods.setFilePath(location);
        goods.setPicturename(s);
            //获取商品分类信息
        int classify = Integer.parseInt(request.getParameter("classify"));
        goods.setClassifys(classify);

        GoodsService service=new GoodsServiceImpl();
        service.goodsinsert(goods);
        response.sendRedirect("product_list.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
    //返回当前时间
    public String timedatenow(){
        //获取当前时间并转成字符串
        DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime ldt=LocalDateTime.now();
        return dtf.format(ldt);
    }
}
